#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "pub_var.h"
#include "dialog_datatrans.h"
#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <QDesktopWidget>
#include <QCloseEvent>
#include <QIcon>
#include <windows.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("门诊简易系统 Ver 0.1 by D.P. Sun");
    qDebug()<<"system start!";

    dlg_cfdy = NULL;    //处方打印
    dlg_gh = NULL;         //挂号
    dlg_gh_env = NULL; //挂号环境配置
    formDocApply = NULL;//医生出诊安排
    formDrugItems = NULL;//在用药品品种管理
    formDrugQuery = NULL; //药品查询
    form_sk = NULL;  //收款
    form_tf = NULL;  //退费
    changePassword = NULL;  //修改口令
    gzltj = NULL; //收费工作量统计
    cftj = NULL;    //处方统计
    jcmlxz = NULL;  //基础目录下载
    xmdz = NULL;  //项目对照
    jsdz = NULL;  //结算对账
    xxcx = NULL;  //信息查询
    dzbl = NULL;  //电子病历
    ybhj = NULL;  //医保环境设置

    iteminout = NULL;//入出记账

    QSize s;

    s.setWidth( QApplication::desktop()->height()/20);
    s.setHeight(QApplication::desktop()->height()/20);
    ui->tbMain->setIconSize(s);

    ui->menu_sk->setEnabled(false);
    ui->menu_tj->setEnabled(false);
    ui->menu_ys->setEnabled(false);
    ui->menu_yb->setEnabled(false);


    qro = QSqlQuery(pub::db_o);
    //C 门诊  F  财务 P  药房
    //qro.exec("select dept_type from com_department where dept_code in"
     //        " ( select distinct p.dept_code from com_employee e, com_priv_user p where "
     //        " e.dept_code = p.grant_dept and p.user_code = '" + pub::usr_code + "')");
    qro.exec("select dept_type from com_department where dept_code in"
             " ( select distinct p.dept_code from com_priv_user p where "
             "  p.user_code = '" + pub::usr_code + "')");

    while(qro.next()){
        if(qro.value(0).toString() == "F"){ //财务
            ui->menu_sk->setEnabled(true);
            ui->tbMain->addSeparator();
            ui->tbMain->addAction(ui->actionreg);
            ui->tbMain->addAction(ui->action_sk);
            ui->tbMain->addAction(ui->action_tf);
            ui->tbMain->addAction(ui->actionGzltj);
        }
        if(qro.value(0).toString() == "P"){ //药局
            ui->menu_tj->setEnabled(true);
            ui->tbMain->addSeparator();
            ui->tbMain->addAction(ui->action_InOut);
            ui->tbMain->addAction(ui->action_drugQuery);
            ui->tbMain->addAction(ui->action_cfdy);
        }
        if(qro.value(0).toString() == "C"){ //门诊医生
            ui->menu_ys->setEnabled(true);
            ui->tbMain->addSeparator();
            ui->tbMain->addAction(ui->actionDocApply);
        }
        if(qro.value(0).toString() == "A"){ //系统管理
            ui->menu_yb->setEnabled(true);
        }
        ui->menu_yb->setEnabled(true);

    }
    ui->tbMain->addSeparator();
    ui->tbMain->addAction(ui->actionexit);

    this->setGeometry(0, 0, QApplication::desktop()->width() -50, 10);
    statusBar()->setVisible(false);
    //statusBar()->showMessage("Status is here...", 3000);

    connect(ui->actionreg,SIGNAL(triggered()),this,SLOT(reg_trigged()));
    connect(ui->actionexit,SIGNAL(triggered()),this,SLOT(exit_trigged()));
    connect(ui->actiondatatrans,SIGNAL(triggered()),this,SLOT(data_trans_triggerd()));
    connect(ui->action_ghsz,SIGNAL(triggered()),this,SLOT(action_ghsz_trigged()));
    connect(ui->action_cfdy,SIGNAL(triggered()),this,SLOT(action_cfdy_trigged()));
    connect(ui->actionDrugItems,SIGNAL(triggered()),this,SLOT(actionDrugItems_trigged()));
    connect(ui->actionDocApply,SIGNAL(triggered()),this,SLOT(actionDocApply_trigged()));
    connect(ui->action_drugQuery,SIGNAL(triggered()),this,SLOT(action_drugQuery_trigged()));
    connect(ui->action_sk,SIGNAL(triggered()),this,SLOT(action_sk_trigged()));
    connect(ui->action_tf,SIGNAL(triggered()),this,SLOT(action_tf_trigged()));
    connect(ui->actionChangePass,SIGNAL(triggered()),this,SLOT(action_changePass_trigged()));
    connect(ui->actionGzltj,SIGNAL(triggered()),this,SLOT(action_gzltj_trigged()));
    connect(ui->action_cftj,SIGNAL(triggered()),this,SLOT(action_cftj_trigged()));
    connect(ui->action_jcmlxz,SIGNAL(triggered()),this,SLOT(action_jcmlxz_trigged()));
    connect(ui->action_xmdz,SIGNAL(triggered()),this,SLOT(action_xmdz_trigged()));
    connect(ui->action_zdwh,SIGNAL(triggered()),this,SLOT(action_zdwh_trigged()));
    connect(ui->action_xxcx,SIGNAL(triggered()),this,SLOT(action_xxcx_trigged()));
    connect(ui->action_jsdz,SIGNAL(triggered()),this,SLOT(action_jsdz_trigged()));
    connect(ui->action_dzbl,SIGNAL(triggered()),this,SLOT(action_dzbl_trigged()));
    connect(ui->action_ybhj,SIGNAL(triggered()),this,SLOT(action_ybhj_trigged()));
    connect(ui->action_InOut,SIGNAL(triggered()),this,SLOT(action_InOut_trigged()));

    tm = new QTimer;
    tm2 = new QTimer;
    connect(tm, SIGNAL(timeout()), this, SLOT(updateTitle()));
    connect(tm2, SIGNAL(timeout()), this, SLOT(waitInitFinish()));

    QSettings setIni("clin.ini", QSettings::IniFormat);

    //本机读卡器型号
    pub::local_carddriver = setIni.value("insurance/carddriver").toString();  //本机读卡器型号

    //获取本机工作IP
    QString iptmp = setIni.value("sys/ip").toString();
    QStringList ips;
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list){
        if(address.protocol() == QAbstractSocket::IPv4Protocol){ //IPv4地址
            ips <<address.toString();
        }
    }
    foreach(QString ip, ips){
        if(ip.indexOf(iptmp) >=0){
            pub::localIP = ip;
            break;
        }
    }

    if(pub::localIP.isEmpty()){//无匹配，选第一项作为默认
        pub::localIP = ips[0];
    }

    qro.exec("update com_loginlog set log_address = '" + pub::localIP + "' "
             " where log_index = '" + pub::LOGINSESSION + "'");

    //本机Mac
    // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();

    for(int i = 0; i < nCnt; i ++){
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp)
                && nets[i].flags().testFlag(QNetworkInterface::IsRunning)
                && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            pub::localMac = nets[i].hardwareAddress();
            break;
        }
    }

    //设置本机工作参数

    qrm = QSqlQuery(pub::db_m);
    qrm.exec("select hos_name,hos_code,new_hos_ybbh, new_hos_ybjy_ip, new_hos_ybjy_port, new_hos_ybjy_tail,"
             " new_hos_dzpz_ip, new_hos_dzpz_port, new_hos_dzpz_tail, new_hos_insuplc ,"
             " new_hos_hiscode, new_hos_secretcode, hos_ybbh "
             " from com_hospitalinfo where valid_Flag = '1'");
    if(qrm.next()){
        pub::hos_name = qrm.value(0).toString();
        pub::hos_code = qrm.value(1).toString();
        pub::hos_ybbh = qrm.value(2).toString();    //医保编号
        pub::hos_ybjy_ip = qrm.value(3).toString();    //医保交易中台
        pub::hos_ybjy_port = qrm.value(4).toString();    //医保交易中台
        pub::hos_ybjy_tail = qrm.value(5).toString();    //医保交易中台
        pub::hos_dzpz_ip = qrm.value(6).toString();    //电子凭证中台
        pub::hos_dzpz_port = qrm.value(7).toString();    //电子凭证中台
        pub::hos_dzpz_tail = qrm.value(8).toString();    //电子凭证中台
        pub::hos_insuplc = qrm.value(9).toString();    //参保区划
        pub::hos_hiscode = qrm.value(10).toString(); //  开发商代码
        pub::hos_secretcode = qrm.value(11).toString(); //  安全管理码
        pub::hos_ybbh_old = qrm.value(12).toString(); //  旧医保编号

        pub::hos_ybjy = "http://" + pub::hos_ybjy_ip + ":" + pub::hos_ybjy_port + pub::hos_ybjy_tail;
        pub::hos_dzpz = "http://" + pub::hos_dzpz_ip + ":" + pub::hos_dzpz_port + pub::hos_dzpz_tail;
    }else{
        QMessageBox::information(this,"error","Can not load system envirenment from MySQL!");
    }

    //初始化医保动态库环境
    qDebug()<<"initialYb";
    ybBusiness = new ThreadYb(this);
    ybBusiness->moveToThread(&thread);
    qDebug()<<"start";
    thread.start();
    QMetaObject::Connection connRet =
    connect(this, SIGNAL(opThread(int, QString)), ybBusiness, SLOT(doWork(int, QString)));
    Q_ASSERT(connRet);
    QFile f;
    QString i = setIni.value("insurance/insurance").toString();
    if(f.exists("HeaSecReadInfo.dll") && i == "1"){    //库文件存在且允许使用
        lib.setFileName("HeaSecReadInfo");
        if(lib.load()){
            //pub::BUSINESS = (pub::pBUSINESS)lib.resolve("BUSINESS_HANDLE");
            pub::Init = (pub::pInit)lib.resolve("Init");
            pub::DailySinIn = (pub::pDailySinIn)lib.resolve("DailySinIn");
            pub::EcQuery = (pub::pEcQuery)lib.resolve("EcQuery");
            pub::ReadSFZ = (pub::pReadSFZ)lib.resolve("ReadSFZ");
            pub::ReadCardBas = (pub::pReadCardBas)lib.resolve("ReadCardBas");
            pub::ChangePIN = (pub::pChangePIN)lib.resolve("ChangePIN");

            QMetaObject::Connection connRet =
            connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
                    this, SLOT(handleInitial(int, QString, QString)));
            Q_ASSERT(connRet);
            //statusBar()->setVisible(true);
            this->setWindowTitle("医保环境初始化 ");

            tm->start(500);

            QJsonObject in;

            QString lgpt = QCoreApplication::applicationDirPath();
            lgpt.append("/dll_logs/");

            in.insert("IP", pub::hos_ybjy_ip);//	服务端IP地址
            in.insert("PORT", pub::hos_ybjy_port);//	服务端端口
            in.insert("TIMEOUT", "15");//	超时
            in.insert("LOG_PATH", lgpt);//	动态库日志目录
            in.insert("EC_URL", pub::hos_dzpz);//	电子凭证中台URL
            in.insert("DRIVER", pub::local_carddriver);//	读卡机具厂家类型
            in.insert("API_NAME", "");//	CSB的_api_name
            in.insert("API_VERSION", "");//	CSB的_api_version
            in.insert("ACCESS_KEY", "");//	CSB的_api_access_key
            in.insert("SECRETKEY", "");//	CSB的secretKey
            in.insert("ORG_ID", pub::hos_ybbh);//	定点编号
            in.insert("AREA_CODE", pub::hos_insuplc);//	定点所属行政区划代码
            in.insert("EXT", "");//	JSON对象字符串

            QJsonDocument indoc ;
            indoc.setObject(in);

            qDebug()<<"Initial"<<indoc;


            QString sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
                 "('dllInit','" + pub::usr_code
                    + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'init','"+ indoc.toJson(QJsonDocument::Compact) +"','')";
            if(!qrm.exec(sq)){
                QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
                qDebug()<<"initial in :" + sq;
            }

            QString inp = indoc.toJson();
            initFinished = false;
            tm2->start(500);    //查询初始化是否完成
            emit opThread(0, inp);
        }else{
            qDebug()<<("load HeaSecReadInfo failed.");
        }

    }else{
        qDebug()<<" HeaSecReadInfo not exist or not allowed.";
    }

    naManager = new QNetworkAccessManager(this); // new QNetworkAccessManager(this);

    connRet = QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)),
                             this, SLOT(postRequestFinished(QNetworkReply*)));

    Q_ASSERT(connRet);

    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setRawHeader("his-code", pub::hos_hiscode.toLatin1());//开发商代码
    //request.setRawHeader("secret-code", pub::hos_secretcode.left(16).toLatin1());//安全管理码

    //ybSign();   //新医保登录
}

void MainWindow::waitInitFinish()
{
    if(initFinished){
        tm2->stop();
        ybSign();   //新医保登录
        ybSigned = true;
        pub::useInsurance = true;  //医保可用
        tm->stop();
    }
}
void MainWindow::updateTitle()
{
    //qDebug()<<"updateTitle";
    QString t = this->windowTitle();
    t = t +" .";
    this->setWindowTitle(t);

}

void MainWindow::handleInitial(const int r, const QString o1, const QString o2  )
{
    qDebug()<<"receive the resultReady signal";

    disconnect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
               this, SLOT(handleInitial(int, QString, QString)));


    if(r != 0){
        //动态库初始化失败
        QMessageBox::information(NULL, "error", "动态库初始化失败：" + o1);
        qDebug()<<"HeaSecReadInfo initial error"<<o1;
        tm->stop(); //停止显示。
        QString sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
             "('dllInit','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'init','','"
                + o1 + "^" + o2 + "')"; //.toUtf8()
        if(!qrm.exec(sq)){
            QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
            qDebug()<<"initial out : " + sq;
        }
    }else{

//        //检查是否存在本日动态库签到记录
//        qro.exec("select * from com_loginlog where login_date > trunc(sysdate)"
//                 " and group_name ='signed' and empl_code = '" + pub::usr_code + "'");
//        if(!qro.next()){
//            //无签到记录，开始动态库签到
//            char outp[1024];
//            int r = pub::DailySinIn(outp);  //动态库日签到
//            qDebug()<<"DailySinIn First sign in "<<r;
//            if( r != 0){
//                QString o = QString::fromLocal8Bit(outp);
//                QMessageBox::information(NULL, "error", "动态库签到失败：" + o);
//                qDebug()<< o;
//                tm->stop();//停止显示。
//            }else{
//                qDebug()<<"DailySinIn sign in success";
//                //保存签到状态
//                qro.exec("update com_loginlog set group_name = 'signed' "
//                 " where log_index = '" + pub::LOGINSESSION + "'");
//            }
//        }else{
//                qDebug()<<"system has been run DailySinIn one times";
//                ybSigned = true;
//                pub::useInsurance = true;  //医保可用
//        }
            //qDebug()<<"system DailySinIn ";
        initFinished = true;    //设置动态库初始化成功标志，以启动医保日签到
    }
    //tm->stop();

    //statusBar()->setVisible(false);
    this->setWindowTitle("门诊简易系统 Ver 0.1 by D.P. Sun");
}


MainWindow::~MainWindow()
{
    delete ui;

    thread.quit();
    thread.wait();

    pub::db_m.close();
    pub::db_o.close();
}

void MainWindow::reg_trigged()
{
    if(dlg_gh == NULL){  //首次加载
        dlg_gh = new Dialog_gh();
    }
    dlg_gh->show();
    if(dlg_gh->isMinimized()){    //如最小化，恢复正常
        dlg_gh->showNormal();
    }

}

void MainWindow::exit_trigged()
{
    this->close();
}

void MainWindow::data_trans_triggerd()
{
    Dialog_datatrans * dlg = new Dialog_datatrans();
    //dlg->setModal(true);
    dlg->show();
}

void MainWindow::action_ghsz_trigged()
{
    if(dlg_gh_env == NULL){  //首次加载
        dlg_gh_env = new Dialog_gh_env();
    }
    dlg_gh_env->show();
    if(dlg_gh_env->isMinimized()){    //如最小化，恢复正常
        dlg_gh_env->showNormal();
    }

}

void MainWindow::action_cfdy_trigged()
{

    if(dlg_cfdy == NULL){  //首次加载
        dlg_cfdy = new Dialog_cfdy();
    }
    dlg_cfdy->show();
    if(dlg_cfdy->isMinimized()){    //如最小化，恢复正常
        dlg_cfdy->showNormal();
    }

}

void MainWindow::actionDocApply_trigged()
{
    if(formDocApply == NULL){  //首次加载
        formDocApply = new FormDocApply();
    }
    formDocApply->show();
    if(formDocApply->isMinimized()){    //如最小化，恢复正常
        formDocApply->showNormal();
    }
}

void MainWindow::actionDrugItems_trigged()
{
    if(formDrugItems == NULL){  //首次加载
        formDrugItems = new FormDrugItems();
    }
    formDrugItems->show();
    if(formDrugItems->isMinimized()){    //如最小化，恢复正常
        formDrugItems->showNormal();
    }
}

void MainWindow::action_drugQuery_trigged()
{
    if(formDrugQuery == NULL){  //首次加载
        formDrugQuery = new FormDrugQuery();
    }
    formDrugQuery->show();
    if(formDrugQuery->isMinimized()){    //如最小化，恢复正常
        formDrugQuery->showNormal();
    }
    connect(formDrugQuery, SIGNAL(destroyW(QString)), this,SLOT(destroyWind(QString)));
}

void MainWindow::action_sk_trigged()
{
    if(form_sk == NULL){  //首次加载
        form_sk = new Form_sk();
    }
    form_sk->show();
    if(form_sk->isMinimized()){    //如最小化，恢复正常
        form_sk->showNormal();
    }
}

void MainWindow::action_tf_trigged()
{
    if(form_tf == NULL){  //首次加载
        form_tf = new Form_tf();
    }
    form_tf->show();
    if(form_tf->isMinimized()){    //如最小化，恢复正常
        form_tf->showNormal();
    }
}

void MainWindow::action_changePass_trigged()
{
    if(changePassword == NULL){  //首次加载
        changePassword = new Form_chagePassword();
    }
    changePassword->show();
    if(changePassword->isMinimized()){    //如最小化，恢复正常
        changePassword->showNormal();
    }
}

void MainWindow::action_gzltj_trigged()
{
    if(gzltj == NULL){  //首次加载
        gzltj = new Form_gzltj();
    }
    gzltj->show();
    if(gzltj->isMinimized()){    //如最小化，恢复正常
        gzltj->showNormal();
    }
}

void MainWindow::action_cftj_trigged()
{
    if(cftj == NULL){  //首次加载
        cftj = new Form_recipeAcount();
    }
    cftj->show();
    if(cftj->isMinimized()){    //如最小化，恢复正常
        cftj->showNormal();
    }
}

void MainWindow::action_jcmlxz_trigged()
{
    if(jcmlxz == NULL){  //首次加载
        jcmlxz = new Form_jcmlxz();
    }
    jcmlxz->show();
    if(jcmlxz->isMinimized()){    //如最小化，恢复正常
        jcmlxz->showNormal();
    }
}

void MainWindow::action_xmdz_trigged()
{
    if(xmdz == NULL){  //首次加载
        xmdz = new Form_xmdz();
    }
    xmdz->show();
    if(xmdz->isMinimized()){    //如最小化，恢复正常
        xmdz->showNormal();
    }
}

void MainWindow::action_zdwh_trigged()
{
    if(xmdz == NULL){  //首次加载
        xmdz = new Form_xmdz();
    }
    xmdz->show();
    if(xmdz->isMinimized()){    //如最小化，恢复正常
        xmdz->showNormal();
    }
}

void MainWindow::action_xxcx_trigged()
{
    if(xxcx == NULL){  //首次加载
        xxcx = new Form_xxcx();
    }
    xxcx->show();
    if(xxcx->isMinimized()){    //如最小化，恢复正常
        xxcx->showNormal();
    }
}

void MainWindow::action_jsdz_trigged()
{
    if(jsdz == NULL){  //首次加载
        jsdz = new Form_jsdz();
    }
    //jsdz->setAttribute(Qt::WA_DeleteOnClose);
    jsdz->show();
    if(jsdz->isMinimized()){    //如最小化，恢复正常
        jsdz->showNormal();
    }
}

void MainWindow::action_dzbl_trigged()
{
    if(dzbl == NULL){  //首次加载
        dzbl = new Form_dzbl();
    }
    //jsdz->setAttribute(Qt::WA_DeleteOnClose);
    dzbl->show();
    if(dzbl->isMinimized()){    //如最小化，恢复正常
        dzbl->showNormal();
    }
}

void MainWindow::action_ybhj_trigged()
{
    if(ybhj == NULL){  //首次加载
        ybhj = new Form_ybhj();
    }
    //jsdz->setAttribute(Qt::WA_DeleteOnClose);
    ybhj->show();
    if(ybhj->isMinimized()){    //如最小化，恢复正常
        ybhj->showNormal();
    }
}

void MainWindow::action_InOut_trigged()
{
    if(iteminout == NULL){  //首次加载
        iteminout = new Form_input();
    }
    iteminout->show();
    if(iteminout->isMinimized()){    //如最小化，恢复正常
        iteminout->showNormal();
    }
    connect(iteminout, SIGNAL(destroyW(QString)), this,SLOT(destroyWind(QString)));
}

void MainWindow::ybSign()
{
    QString inp;
    QString msgid;  //发送方报文ID ,定点医药机构编号(12)+时间(14)+顺序号(4)  时间格式：yyyyMMddHHmmss

    inp = pub::getYbStrJ("9001","");   //签到
    if(inp.isEmpty()){
        qDebug()<<"ybSign inp is null";
        QMessageBox::information(NULL,"note","申请交易流水号失败！");
        return ; //未能成功申请交易流水号
    }
    currentMsgid = inp;
    currentInfno = "9001";
    //msgid = pub::hos_ybbh + inp;
    msgid = inp;

    QJsonObject in;
    in.insert("infno", "9001");
    in.insert( "msgid", msgid);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    in.insert("insuplc_admdvs","");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", "");

    QJsonObject inpu,inpud;
    inpu.insert("opter_no", pub::usr_code); //操作员编号
    inpu.insert("mac", pub::localMac);//签到MAC地址
    inpu.insert("ip",pub::localIP);//签到IP地址
    inpud.insert("signIn",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
qDebug()<<"9001 indoc "<<indoc;
//保存入参日志
qrm.exec("update com_business set v_in = '"
         + indoc.toJson(QJsonDocument::Compact)
         + "' where jyls = '" + currentMsgid + "'");
    rpl = naManager->post(request, indoc.toJson());

}
void MainWindow::postRequestFinished(QNetworkReply *)
{
    httpFinished = true;
    tm->stop();
    QVariant statusCode = rpl->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","9001 http 请求状态错误: " + statusCode.toString());
        ybSigned = false;

        return;
    }
    //QVariant reason = rpl->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    //if(!reason.isValid()){
    //    QMessageBox::warning(this,"注意",reason.toString());
    //    ybSigned = false;
    //    return;
    //}
    QNetworkReply::NetworkError err = rpl->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意","9001:"+rpl->errorString());
        ybSigned = false;

        return;
    }else{
        QByteArray bt = rpl->readAll();
        QString t = QString::fromLocal8Bit(bt);
        qDebug()<<"outDoc"<<t;
        QJsonParseError json_error;
        QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
        if(json_error.error != 0 ){
            QMessageBox::warning(NULL,"注意","9001返回信息解析错误 " + json_error.errorString());
            ybSigned = false;

            return;
        }
        QJsonObject jsob = jsdc.object();

        qrm.exec("update com_business set v_out = '"
                 + jsdc.toJson(QJsonDocument::Compact)
                 + "' where jyls = '" + currentMsgid + "'");

        qDebug()<<"9001 return is "<<jsdc;
        if(jsob.value("infcode").toInt() != 0){
            QString t = jsob.value("err_msg").toString();
            QMessageBox::warning(NULL,"注意","交易失败:" + t );
        }else if(currentInfno == "9001"){
            QJsonObject jsobo = jsob.value("output").toObject().value("signinoutb").toObject();

            pub::sign_no = jsobo.value("sign_no").toString();
            pub::sign_time = jsobo.value("sign_time").toString();
            ybSigned = true;
            qDebug()<<pub::sign_no;
            qDebug()<<pub::sign_time;
            qDebug()<<"ybSigned";
        }else if(currentInfno == "9002"){
            QJsonObject jsobo = jsob.value("output").toObject().value("signoutoutb").toObject();
            pub::sign_time = jsobo.value("sign_time").toString();
            qDebug()<<pub::sign_time;
            qDebug()<<"ybSign";
            return; // 注销操作，后续操作无用，直接返回。
        }
        pub::useInsurance = true;  //医保可用

        QString inp = pub::getYbStrJ("5270","");   //签到
        if(inp.isEmpty()){

            QMessageBox::information(NULL,"note"," 5270 申请交易流水号失败！");
            return ; //未能成功申请交易流水号
        }
        currentInfno = "5270";

        QJsonObject in;

        in.insert("infno", "5270");
        in.insert( "msgid", inp);
        in.insert("mdtrtarea_admvs", pub::hos_insuplc);
        in.insert("insuplc_admdvs","");
        in.insert("recer_sys_code", "OwnSoft");
        in.insert("dev_no","");
        in.insert("dev_safe_info","");
        in.insert("cainfo", pub::hos_secretcode);
        in.insert("signtype","");
        in.insert("infver", "V1.0");
        in.insert("opter_type", "1");
        in.insert("opter", pub::usr_code);
        in.insert("opter_name", pub::usr_name);
        in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
        in.insert("fixmedins_code", pub::hos_ybbh);
        in.insert("fixmedins_name", pub::hos_name);
        in.insert("sign_no", "");

        QJsonDocument indoc ;
        indoc.setObject(in);

        qDebug()<<"5270 indoc "<<indoc;

        //保存入参日志
        QString sq = "update com_business set v_in = '"
                + indoc.toJson(QJsonDocument::Compact)
                + "' where jyls = '" + inp + "'";

        if(!qrm.exec(sq)){
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }

        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        QNetworkAccessManager manager;
        QNetworkReply* rep = manager.post(request,indoc.toJson());

        QEventLoop eventLoop;
        QObject::connect(rep, SIGNAL(finished()), &eventLoop, SLOT(quit()));
        eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

        QVariant statusCode = rep->attribute(QNetworkRequest::HttpStatusCodeAttribute);

        if(!statusCode.isValid()){
            QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
            return ;
        }

        QNetworkReply::NetworkError err = rep->error();

        if(err != QNetworkReply::NoError){
            QMessageBox::warning(NULL,"注意",rep->errorString());
            return ;
        }

        bt = rep->readAll();
        t = QString::fromLocal8Bit(bt);

        jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
        if(json_error.error != 0 ){
            QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
            return ;
        }
        qDebug()<< "5270 outDoc "<<jsdc;
        jsob = jsdc.object();

        sq = "update com_business set v_out = '"
                + jsdc.toJson(QJsonDocument::Compact)
                + "' where jyls = '" + inp + "'";

        if(!qrm.exec(sq)){
            QMessageBox::information(this,"错误","保存出参日志失败！");
            qDebug()<<sq;
        }


        if(jsob.value("infcode").toInt() != 0){
            QString t = jsob.value("err_msg").toString();
            QMessageBox::warning(NULL,"注意","5270 交易失败：" + t );

            return ;
        }
        QJsonObject ret = jsob.value("output").toObject().value("result").toObject();
        QString dtstr = ret.value("cent_time").toVariant().toString();
        QDateTime dttm = QDateTime::fromString(dtstr, "yyyyMMddHHmmss");

        SYSTEMTIME st;
        GetLocalTime(&st); // Win32 API 获取系统当前时间，并存入结构体st中

qDebug()<<dtstr;
qDebug()<<"before "<<QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

        st.wYear = dttm.date().year();
        st.wMonth = dttm.date().month();
        st.wDay = dttm.date().day();
        st.wHour = dttm.time().hour();
        st.wMinute = dttm.time().minute();
        st.wSecond = dttm.time().second();
        //st.wMilliseconds = dttm.time().msec();
        SetLocalTime(&st);    //Win32 API 设置系统时间
qDebug()<<"after "<<QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
        return;
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    //|窗口关闭之前需要的操作~
    QMessageBox:: StandardButton result= QMessageBox::warning(NULL, "注意", "确定要退出管理系统？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No){
        event->ignore();
        return;
    }

    if(!pub::sign_no.isEmpty()){

        QString inp;

        inp = pub::getYbStrJ("9002","");   //签到
        if(inp.isEmpty()){
            QMessageBox::information(NULL,"note","申请交易流水号失败！");
            //直接退出
        }else{
            currentInfno = "9002";
            currentMsgid = inp;

            QJsonObject in;
            in.insert("infno", "9002");
            in.insert( "msgid", currentMsgid);
            in.insert("mdtrtarea_admvs", pub::hos_insuplc);
            in.insert("insuplc_admdvs","");
            in.insert("recer_sys_code", "OwnSoft");
            in.insert("dev_no","");
            in.insert("dev_safe_info","");
            in.insert("cainfo", pub::hos_secretcode);
            in.insert("signtype","");
            in.insert("infver", "V1.0");
            in.insert("opter_type", "1");
            in.insert("opter", pub::usr_code);
            in.insert("opter_name", pub::usr_name);
            in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
            in.insert("fixmedins_code", pub::hos_ybbh);
            in.insert("fixmedins_name", pub::hos_name);
            in.insert("sign_no", pub::sign_no);

            QJsonObject inpu,inpud;
            inpu.insert("opter_no", pub::usr_code); //操作员编号
            inpu.insert("sign_no", pub::sign_no);//签到MAC地址

            inpud.insert("signOut",inpu);
            in.insert("input", inpud);

            QJsonDocument indoc ;
            indoc.setObject(in);
            qDebug()<<"indoc"<<indoc;
            rpl = naManager->post(request, indoc.toJson());

            httpFinished = false;
            QString t0 = this->windowTitle();
            QString t;
            while(true){
                QThread::msleep(330);
                t = this->windowTitle();

                if( t.isEmpty()){
                    t = t0;
                }else{
                    t = "";
                }
                this->setWindowTitle(t);
                qApp->processEvents();
                if(httpFinished){
                    break;
                }
            }
        }
    }

    qro.exec("update com_loginlog set logout_date = sysdate "
             " where log_index = '" + pub::LOGINSESSION + "'");

    if(dlg_cfdy != NULL) delete dlg_cfdy;
    if(dlg_gh != NULL) delete dlg_gh;
    if(dlg_gh_env != NULL) delete dlg_gh_env;
    if(formDocApply != NULL) delete formDocApply;
    if(formDrugItems != NULL) delete formDrugItems;
    if(formDrugQuery != NULL) delete formDrugQuery;
    if(form_sk != NULL) delete form_sk;
    if(form_tf != NULL) delete form_tf;
    if(changePassword != NULL) delete changePassword;
    if(gzltj != NULL) delete gzltj;
    if(cftj != NULL) delete cftj;
    if(jcmlxz != NULL) delete jcmlxz;
    if(xmdz != NULL) delete xmdz;
    if(jsdz != NULL) delete jsdz;
    if(xxcx != NULL) delete xxcx;
    if(dzbl != NULL) delete dzbl;
    if(ybhj != NULL) delete ybhj;
    if(iteminout != NULL) delete iteminout;

}

void MainWindow::destroyWind( QString w)
{
//    QMessageBox::information(this, "note", w);

    if(w == "Form_input"){
        if( iteminout != NULL){
            delete iteminout;
            iteminout = NULL;
        }
    }else if(w == "FormDrugQuery"){
        if( formDrugQuery != NULL){
            delete formDrugQuery;
            formDrugQuery = NULL;
        }
    }

}
